package cn.tpshion.devops.node;

import cn.tpshion.devops.common.enums.MsgType;
import cn.tpshion.devops.common.enums.NodeType;
import cn.tpshion.devops.common.constant.NodeConstant;
import cn.tpshion.devops.domain.entity.MsgData;
import cn.tpshion.devops.domain.entity.NodeData;
import cn.tpshion.devops.handle.LocalCommandHandle;
import cn.tpshion.devops.node.data.NodeJsData;
import cn.tpshion.devops.node.support.NodeContext;
import cn.tpshion.devops.util.AssertUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class NodeJsNode extends Node<NodeJsData> {

    @Override
    public NodeType nodeType() {
        return NodeType.NODEJS;
    }

    @Override
    public void handle(NodeContext nodeContext) throws Exception {
        log.info("NodeJsNode nodeContext:{}", nodeContext);
        Map<String, Object> contextData = nodeContext.getData();
        String workspace = contextData.get(NodeConstant.WORKSPACE).toString();
        NodeJsData data = getData(nodeContext);

        String commandStr = handleCommandStr(data.getCommand(), workspace);
        AssertUtil.isEmpty(commandStr, "命令错误");

        log.info("NodeJsNode command:{}", commandStr);
        sseHandle.sendMessage(nodeContext, new MsgData(MsgType.INFO, "NodeJsNode command: " + commandStr));

        LocalCommandHandle commandHandle = new LocalCommandHandle(sseHandle, nodeContext, workspace);
        commandHandle.exec(commandStr);
    }

    private String handleCommandStr(String command, String workspace){
        if(!StringUtils.hasText(command)){
            return null;
        }

        if(command.contains("#workspace#")){
            command = command.replaceAll("#workspace#", workspace);
        }

        List<String> list = Arrays.stream(StringUtils.delimitedListToStringArray(command, "\n"))
                .filter(i -> StringUtils.hasText(i)).collect(Collectors.toList());
        if(ObjectUtils.isEmpty(list)){
            return null;
        }

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            builder.append(i == 0 ? list.get(i) : " && " + list.get(i));
        }
        return builder.toString();
    }

    @Override
    protected NodeJsData getData(NodeContext nodeContext) {
        NodeData nodeData = nodeContext.getNodeData();
        NodeJsData data = JSON.parseObject(JSON.toJSONString(nodeData.getData()), NodeJsData.class);
        return data;
    }
}
